package com.weipt.rabbitmq;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class HelloSimple {

    public static final String QUEUE_NAME = "hello-simple—queue";

    public static void main(String[] args) throws IOException, TimeoutException {
        publish("test simple");
        consume();
    }

    public static void publish(String msg) throws IOException, TimeoutException {
        Connection mqConn = ConnectionUtils.getMqConn();
        Channel channel = mqConn.createChannel(); //创建一个新的管道
        channel.queueDeclare(QUEUE_NAME, false,false,false,null);
        //因为rabbitmq是长连接，相当于一个连接中可以创建多个管道就行通讯，类比http长连接
        //所有的消息不能直接由channel发给queue，必须要经过exchange，如果不指定，则走默认的exchage，默认的是direct模式。非direct模式无法走默认
        //第二个参数源码是routingkey，实际我们送queuename
        //下面是官网的说法，默认交换机绑定了所有的queue，发消息的时候，路由key就是队列名称
        //The default exchange is implicitly bound to every queue,
        // with a routing key equal to the queue name.
        // It is not possible to explicitly bind to,
        // or unbind from the default exchange. It also cannot be deleted.
        channel.basicPublish("", QUEUE_NAME,  MessageProperties.PERSISTENT_TEXT_PLAIN, msg.getBytes());
        //关闭连接
        channel.close();
        mqConn.close();
    }

    public static void consume() throws IOException {
        Connection mqConn = ConnectionUtils.getMqConn();
        Channel channel = mqConn.createChannel();
        //Direct模式下是没有routingkey的，所以下面的第二个参数，实际是queueName
        channel.basicConsume(QUEUE_NAME, true, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("handleDelivery:"+consumerTag);
                System.out.println("可以通过重写handleDelivery方法，获取queue中的消息。消息内容："+new String(body));
            }
        });
        //消费端连接与同道不用关闭，一直处于监听状态
        //channel.close();
        //mqConn.close();
    }
}
